﻿Imports System.Data
Imports MyGeneration.dOOdads
Imports ClassSigeco.ClassSigeco
Imports System.Text
Imports System.Security.Cryptography

Public Class controller_sistema

    Private _MessageError As Exception = Nothing
    Public Property MessageError() As Exception
        Get
            Return _MessageError
        End Get
        Set(ByVal value As Exception)
            _MessageError = value
        End Set
    End Property

#Region "Usuarios"

    Private Function ValidateSHA1HashData(ByVal inputData As String, ByVal storedHashData As String) As Boolean
        'hash input text and save it string variable
        Dim getHashInputData As String = GetSHA1HashData(inputData)

        If String.Compare(getHashInputData, storedHashData) = 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    ''' <summary>
    ''' take any string and encrypt it using SHA1 then
    ''' return the encrypted data
    ''' </summary>
    ''' <param name="data">input text you will enterd to encrypt it</param>
    ''' <returns>return the encrypted text as hexadecimal string</returns>
    Private Function GetSHA1HashData(ByVal data As String) As String
        'create new instance of md5
        Dim sha1__1 As SHA1 = SHA1.Create()

        'convert the input text to array of bytes
        Dim hashData As Byte() = sha1__1.ComputeHash(Encoding.[Default].GetBytes(data))

        'create new instance of StringBuilder to save hashed data
        Dim returnValue As New StringBuilder()

        'loop for each byte and add it to StringBuilder
        For i As Integer = 0 To hashData.Length - 1
            returnValue.Append(hashData(i).ToString())
        Next

        ' return hexadecimal string
        Return returnValue.ToString()
    End Function

    'Public Function Insert_Log(ByVal conn As String, ByVal descripcion As String, ByVal codUsuario As Integer, ByVal codFuncion As Integer, Optional ByVal dt As DataTable = Nothing) As Integer

    '    Dim tx As TransactionMgr
    '    tx = TransactionMgr.ThreadTransactionMgr()

    '    Try
    '        tx.BeginTransaction()

    '        Dim datos As String = ""
    '        If Not dt Is Nothing Then
    '            For x As Integer = 0 To dt.Rows.Count - 1
    '                For i As Integer = 0 To dt.Columns.Count - 1
    '                    datos += dt.Columns(i).ColumnName & ": " & dt.Rows(x)(i).ToString() & " | " '& Environment.NewLine
    '                Next
    '            Next
    '        End If

    '        Dim usu As New Class_RC_Data.Class_RC.LOG(conn)

    '        usu.AddNew()
    '        usu.Descripcion = descripcion
    '        usu.Fecha = DateTime.Now
    '        usu.CodUsuario = codUsuario
    '        usu.CodFuncion = codFuncion
    '        usu.Datos = datos
    '        usu.Save()

    '        tx.CommitTransaction()

    '        Return usu.CodLog

    '    Catch ex As Exception
    '        tx.RollbackTransaction()
    '        MessageError = ex
    '        Return 0
    '    End Try

    'End Function

    Public Function Insert_Caja_Registro(ByVal conn As String, ByVal idUsuario As Integer, ByVal fechaApertura As DateTime, _
                                         ByVal fechaCierre? As DateTime, ByVal idResponsable As Integer, _
                                         ByVal montoApertura As Decimal, ByVal montoCierre As Decimal, _
                                        ByVal comentarios As String) As Integer

        Dim tx As TransactionMgr
        tx = TransactionMgr.ThreadTransactionMgr()

        Try
            tx.BeginTransaction()
            'aca log
            Dim usu As New ClassSigeco.ClassSigeco.si_caja(conn)

            usu.AddNew()
            usu.IdUsuario = idUsuario
            usu.FechaApertura = fechaApertura

            If Not fechaCierre Is Nothing Then
                usu.FechaCierre = fechaCierre
            End If

            usu.IdResponsable = idResponsable
            usu.MontoApertura = montoApertura
            usu.MontoCierre = montoCierre
            usu.SaldoEfectivo = montoApertura
            usu.Comentarios = comentarios
            usu.Save()

            tx.CommitTransaction()

            Return usu.IdMovimientoCaja

        Catch ex As Exception
            tx.RollbackTransaction()
            MessageError = ex
            Return 0
        End Try

    End Function

    Public Function Update_Caja_Registro(ByVal conn As String, ByVal idMovimiento As Integer, _
                                         ByVal idUsuario As Integer, ByVal fechaApertura As DateTime, _
                                         ByVal fechaCierre? As DateTime, ByVal idResponsable As Integer, _
                                         ByVal montoApertura As Decimal, ByVal montoCierre As Decimal, _
                                         ByVal comentarios As String, ByVal montoDiferencia As Decimal) As Boolean

        Dim tx As TransactionMgr
        tx = TransactionMgr.ThreadTransactionMgr()

        Try
            tx.BeginTransaction()
            'aca log

            Dim usu As New ClassSigeco.ClassSigeco.si_caja(conn)
            usu.Where.IdMovimientoCaja.Value = idMovimiento
            If usu.Query.Load Then
                usu.IdUsuario = idUsuario
                usu.FechaApertura = fechaApertura

                If Not fechaCierre Is Nothing Then
                    usu.FechaCierre = fechaCierre
                End If

                usu.IdResponsable = idResponsable
                usu.MontoApertura = montoApertura
                usu.MontoCierre = montoCierre
                usu.Diferencia = montoDiferencia
                usu.Comentarios = comentarios
                usu.Save()
            End If

            tx.CommitTransaction()
            Return True

        Catch ex As Exception
            tx.RollbackTransaction()
            MessageError = ex
            Return False
        End Try

    End Function

    Public Function Delete_Caja_Registro(ByVal conn As String, ByVal IdMovimiento As Integer, ByVal idUsuario As Integer) As Boolean

        Dim tx As TransactionMgr
        tx = TransactionMgr.ThreadTransactionMgr()

        Try
            tx.BeginTransaction()

            Dim usu As New ClassSigeco.ClassSigeco.si_caja(conn)
            usu.Where.IdMovimientoCaja.Value = IdMovimiento

            If usu.Query.Load Then

                usu.BorradoPor = idUsuario
                usu.BorradoFecha = DateTime.Now
                usu.Save()

            End If

            tx.CommitTransaction()
            Return True

        Catch ex As Exception
            tx.RollbackTransaction()
            MessageError = ex
            Return False
        End Try

    End Function

    Public Function get_Caja_Actual(ByVal conn As String, ByVal idUsuario As Integer) As Integer
        Try

            Dim usu As New ClassSigeco.ClassSigeco.si_caja(conn)

            usu.Where.IdUsuario.Value = idUsuario
            usu.Where.FechaCierre.Value = 0
            usu.Where.FechaCierre.Operator = WhereParameter.Operand.IsNull

            usu.Query.AddOrderBy("idMovimientoCaja", WhereParameter.Dir.DESC)

            If usu.Query.Load Then
                If usu.DefaultView.Table.Rows.Count > 0 Then
                    Return usu.DefaultView.Table.Rows(0)("idMovimientoCaja")
                Else
                    Return 0
                End If

            Else
                Return 0

            End If

        Catch ex As Exception
            MessageError = ex
            Return 0
        End Try

    End Function

    Public Function get_Caja_Datos(ByVal conn As String, ByVal idMovimiento As Integer) As DataTable
        Try

            Dim usu As New ClassSigeco.ClassSigeco.vw_caja(conn)
            usu.Where.IdMovimientoCaja.Value = idMovimiento

            'usu.Where.IdUsuario.Value = idUsuario
            'usu.Where.FechaCierre.Value = 0
            'usu.Where.FechaCierre.Operator = WhereParameter.Operand.IsNull

            usu.Query.AddOrderBy("idMovimientoCaja", WhereParameter.Dir.DESC)

            If usu.Query.Load Then
                If usu.DefaultView.Table.Rows.Count > 0 Then
                    Return usu.DefaultView.Table
                Else
                    Return Nothing
                End If

            Else
                Return Nothing

            End If

        Catch ex As Exception
            MessageError = ex
            Return Nothing
        End Try

    End Function

    Public Function get_Caja_All(ByVal conn As String, ByVal idMovimientoCaja As Integer, _
                                    ByVal fechaInicio? As DateTime, ByVal fechaFin? As DateTime) As DataTable
        Try

            Dim usu As New ClassSigeco.ClassSigeco.si_caja(conn)

            If idMovimientoCaja > 0 Then
                usu.Where.IdMovimientoCaja.Value = idMovimientoCaja
            End If

            If Not fechaInicio Is Nothing And Not fechaFin Is Nothing Then
                usu.Where.FechaApertura.BetweenBeginValue = New DateTime(New DateTime(fechaInicio.ToString()).Year, New DateTime(fechaInicio.ToString()).Month, New DateTime(fechaInicio.ToString()).Day, 0, 0, 0)
                usu.Where.FechaApertura.BetweenEndValue = New DateTime(New DateTime(fechaFin.ToString()).Year, New DateTime(fechaFin.ToString()).Month, New DateTime(fechaFin.ToString()).Day, 23, 59, 59)
                usu.Where.FechaApertura.Operator = WhereParameter.Operand.Between
            End If
            

            usu.Query.AddOrderBy("idMovimientoCaja", WhereParameter.Dir.DESC)

            If usu.Query.Load Then
                If usu.DefaultView.Table.Rows.Count > 0 Then
                    Return usu.DefaultView.Table
                Else
                    Return Nothing
                End If

            Else
                Return Nothing

            End If

        Catch ex As Exception
            MessageError = ex
            Return Nothing
        End Try

    End Function

    Public Function Insert_Usuario(ByVal conn As String, ByVal usuario As String, ByVal pass As String, ByVal nombre As String, _
                                   ByVal documento As String, ByVal tipo As String, ByVal idUsuarioPor As Integer) As Integer

        Dim tx As TransactionMgr
        tx = TransactionMgr.ThreadTransactionMgr()

        Try
            tx.BeginTransaction()
            'aca log
            Dim usu As New ClassSigeco.ClassSigeco.si_usuario(conn)

            usu.AddNew()
            usu.Usuario = usuario
            usu.Contrasenha = GetSHA1HashData(pass)
            usu.Nombre = nombre
            usu.Documento = documento
            usu.TipoUsuario = tipo
            usu.ActualizadoPor = idUsuarioPor
            usu.ActualizadoFecha = DateTime.Now
            usu.Habilitado = True
            usu.Save()

            tx.CommitTransaction()

            Return usu.IdUsuario

        Catch ex As Exception
            tx.RollbackTransaction()
            MessageError = ex
            Return 0
        End Try

    End Function

    Public Function Update_Usuario(ByVal conn As String, ByVal idUsuario As Integer, _
                                   ByVal usuario As String, ByVal pass As String, ByVal nombre As String, _
                                   ByVal documento As String, ByVal tipo As String, ByVal codUsuario As Integer, _
                                   ByVal habilitado As Boolean) As Boolean

        Dim tx As TransactionMgr
        tx = TransactionMgr.ThreadTransactionMgr()

        Try
            tx.BeginTransaction()

            Dim usu As New ClassSigeco.ClassSigeco.si_usuario(conn)
            usu.Where.IdUsuario.Value = idUsuario

            If usu.Query.Load Then

                usu.Usuario = usuario

                If pass <> "" Then
                    usu.Contrasenha = GetSHA1HashData(pass)
                End If

                usu.Nombre = nombre
                usu.Documento = documento
                usu.TipoUsuario = tipo
                usu.ActualizadoPor = codUsuario
                usu.ActualizadoFecha = DateTime.Now
                usu.Habilitado = habilitado
                usu.Save()

            End If

            tx.CommitTransaction()
            Return True

        Catch ex As Exception
            tx.RollbackTransaction()
            MessageError = ex
            Return False
        End Try

    End Function

    Public Function Delete_Usuario(ByVal conn As String, ByVal IdUsuario As Integer) As Boolean

        Dim tx As TransactionMgr
        tx = TransactionMgr.ThreadTransactionMgr()

        Try
            tx.BeginTransaction()

            Dim usu As New ClassSigeco.ClassSigeco.si_usuario(conn)
            usu.Where.IdUsuario.Value = IdUsuario

            If usu.Query.Load Then

                usu.MarkAsDeleted()
                usu.Save()

            End If

            tx.CommitTransaction()
            Return True

        Catch ex As Exception
            tx.RollbackTransaction()
            MessageError = ex
            Return False
        End Try

    End Function

    Public Function Login(ByVal conn As String, ByVal user As String, ByVal pass As String) As Integer

        Dim usuario As New ClassSigeco.ClassSigeco.si_usuario(conn)
        usuario.Where.Usuario.Value = user
        usuario.Where.Contrasenha.Value = GetSHA1HashData(pass)
        If usuario.Query.Load Then
            If usuario.Habilitado Then
                Return usuario.IdUsuario

            Else
                Return -1

            End If

        Else
            Return 0

        End If

    End Function

    Public Function get_Usuario_All(ByVal conn As String, ByVal idUsuario As Integer, _
                                    ByVal usuario As String, ByVal nombre As String, _
                                    ByVal documento As String, ByVal tipo As String) As DataTable
        Try

            Dim usu As New ClassSigeco.ClassSigeco.vw_usuarios(conn)

            If idUsuario > 0 Then
                usu.Where.IdUsuario.Value = idUsuario
            End If

            If usuario <> "" Then
                usu.Where.Usuario.Value = "%" & usuario & "%"
                usu.Where.Usuario.Operator = WhereParameter.Operand.Like
            End If

            If nombre <> "" Then
                usu.Where.Nombre.Value = "%" & nombre & "%"
                usu.Where.Nombre.Operator = WhereParameter.Operand.Like
            End If

            If documento <> "" Then
                usu.Where.Documento.Value = "%" & documento & "%"
                usu.Where.Documento.Operator = WhereParameter.Operand.Like
            End If

            If tipo <> "" Then
                usu.Where.TipoUsuario.Value = "%" & tipo & "%"
                usu.Where.TipoUsuario.Operator = WhereParameter.Operand.Like
            End If

            usu.Query.AddOrderBy("usuario", WhereParameter.Dir.ASC)

            If usu.Query.Load Then
                If usu.DefaultView.Table.Rows.Count > 0 Then
                    Return usu.DefaultView.Table
                Else
                    Return Nothing
                End If

            Else
                Return Nothing

            End If

        Catch ex As Exception
            MessageError = ex
            Return Nothing
        End Try

    End Function

    Public Function get_Log_All(ByVal conn As String, ByVal descripcion As String, ByVal usuario As String, _
                                ByVal fechaInicio As DateTime, ByVal fechaFin As DateTime, ByVal valorAnterior As String, _
                                ByVal valorNuevo As String) As DataTable
        Try

            Dim usu As New ClassSigeco.ClassSigeco.vw_log(conn)

            usu.Where.Fecha.BetweenBeginValue = New DateTime(fechaInicio.Year, fechaInicio.Month, fechaInicio.Day, 0, 0, 0)
            usu.Where.Fecha.BetweenEndValue = New DateTime(fechaFin.Year, fechaFin.Month, fechaFin.Day, 23, 59, 59)
            usu.Where.Fecha.Operator = WhereParameter.Operand.Between

            If usuario <> "" Then
                usu.Where.Usuario.Value = "%" & usuario & "%"
                usu.Where.Usuario.Operator = WhereParameter.Operand.Like
            End If

            If descripcion <> "" Then
                usu.Where.Descripcion.Value = "%" & descripcion & "%"
                usu.Where.Descripcion.Operator = WhereParameter.Operand.Like
            End If

            If valorAnterior <> "" Then
                usu.Where.ValorAnterior.Value = "%" & valorAnterior & "%"
                usu.Where.ValorAnterior.Operator = WhereParameter.Operand.Like
            End If

            If valorNuevo <> "" Then
                usu.Where.ValorNuevo.Value = "%" & valorNuevo & "%"
                usu.Where.ValorNuevo.Operator = WhereParameter.Operand.Like
            End If

            usu.Query.AddOrderBy("fecha", WhereParameter.Dir.DESC)

            If usu.Query.Load Then
                If usu.DefaultView.Table.Rows.Count > 0 Then
                    Return usu.DefaultView.Table
                Else
                    Return Nothing
                End If

            Else
                Return Nothing

            End If

        Catch ex As Exception
            MessageError = ex
            Return Nothing
        End Try

    End Function

#End Region

End Class
